package project.pianpian.config;

import org.springframework.web.servlet.HandlerInterceptor;
import project.pianpian.entity.User;
import project.pianpian.mapper.UserMapper;
import project.pianpian.utils.ReturnUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

import static project.pianpian.utils.Token.verify;

/**
 * description:
 * author :万霁初
 * date :2022/12/26 11:07
 **/
public class LoginInterceptor implements HandlerInterceptor {
    UserMapper userMapper;

    public LoginInterceptor(UserMapper userMapper) {
        super();
        this.userMapper=userMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","*");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers","*");
        if (request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
        }

        response.setContentType("Application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        if (request.getHeader("token")==null||request.getHeader("token").isEmpty()){
            response.getWriter().println(ReturnUtils.fail(500,"缺少token参数"));
            return false;
        }

        String token=request.getHeader("token");
        Map varifyToken=verify(token);

        Date date= (Date) varifyToken.get("deadline");
        if(date.before(new Date())){
            response.getWriter().println(ReturnUtils.fail(500,"token过期"));
            return false;
        }

        int id= (int) varifyToken.get("id");
        User user = userMapper.selectById(id);
        if (user==null){
            response.getWriter().println(ReturnUtils.fail(500,"不存在该token对应的用户"));
            return false;
        }

        return true;
    }
}
